/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Correo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;

/**
 *
 * @author estudiante
 */
public class MailPOP3 extends Conexion {

    public MailPOP3(String dom, int port, String User, String Pass) {
        dominio = dom;
        puerto = port;
        user = User;
        pass = Pass;
    }

    public boolean conectar() {
        try {
            System.out.println(getClass().getName() + " =" + dominio);
            this.socket = new Socket(dominio, this.puerto);
            out = new PrintWriter(this.socket.getOutputStream());
            in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));

            enviarMensaje("USER " + user);
            enviarMensaje("PASS " + pass);
            System.out.println(leer());
            System.out.println("OK CONEXION");
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("Error : Al conectar POP3");
            return false;
        }
    }

    public Mail recibir(int index) throws Exception {
        boolean isFin = false;
        enviarMensaje("RETR " + index);
        Mail m = new Mail();
        m.setSubject(null);
        while (!isFin) {
            String cad = leer();
            if (cad.equals(".")) {
                isFin = true;
            }
            //recojo DATE
            if (cad.startsWith("Date:")) {
                System.out.println("DATE = " + cad);
                try {
                    m.setFecha(new Date(cad.replaceAll("Date:", "").trim()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //recojo FROM
            if (cad.startsWith("From:") && cad.indexOf("@") != -1) {
                System.out.println("Form = " + cad);
                cad = cad.replaceFirst("From:", "");
                int ind = cad.indexOf("<");
                if (ind != -1) {
                    m.setOrigen(cad.substring(ind + 1, cad.indexOf(">")));
                } else {
                    m.setOrigen(cad.trim());
                }
            }
            //recojo SUBJECT
            if (cad.startsWith("Subject:") && m.getSubject() == null) {
                System.out.println("Subject = " + cad);
                m.setSubject(cad.replaceFirst("Subject:", ""));
            }
            //recojo TO
            if (cad.startsWith("To:") && cad.indexOf("@") != -1) {
                System.out.println("TO = " + cad);
                cad = cad.replaceFirst("To:", "");
                int ind = cad.indexOf("<");
                if (ind != -1) {
                    m.setDestino(cad.substring(ind + 1, cad.indexOf(">")));
                } else {
                    m.setDestino(cad.trim());
                }
            }
            //recojo DATA
            if (cad.trim().startsWith("&")) {
                String d = obtenerdata();
                d = d.replaceAll("=3D", "=").replaceAll("=3B", ";");
                m.setData(d);
                System.out.println("DATA = " + m.getData().replaceAll("]", ""));
                isFin = true;
            }
        }
        return m;
    }

    private String obtenerdata() throws Exception {
        boolean isFin = false;
        String cad = "";
        int i = 0;
        while (!isFin) {
            String dato = leer();
            System.out.println("..." + cad);
            if (dato.indexOf("/&") != -1) {
                isFin=true;
            } else {
                cad = cad + dato;
            }            
        }
        return cad;
    }

    public void recibir() throws Exception {
        int cantM = getCantC();
        System.out.println("Cantidad de correos recibidos=" + cantM);
        for (int i = 1; i <= cantM; i++) {
            System.out.println("---------------------------Mensaaje Recibido----------------------------");
            Mail m = recibir(i);
            ZRecibidorMail.vectorMails.add(m);
            eliminar(i);
            Thread.sleep(1000);
            System.out.println("---------------------------------fin-------------------------------------");
        }
    }

    public void eliminar(int index) throws Exception {
        enviarMensaje("DELE " + index);
    }

    public int getCantC() throws Exception {
        System.out.println("getcant");
        String linea = enviarMensaje("STAT ");
        if (linea == null) {
            return 0;
        } else {
            String cad[] = linea.split(" ");
            int numero = Integer.valueOf(cad[1]);
            return numero;
        }
    }
}
